package com.ruoyi.business.service.product.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.product.TbProduct;
import com.ruoyi.business.domain.product.TbProductCategories;
import com.ruoyi.business.domain.product.TbProductSkus;
import com.ruoyi.business.domain.vo.product.TbProductVO;
import com.ruoyi.business.mapper.TbProductMapper;
import com.ruoyi.business.service.product.TbProductCategoriesService;
import com.ruoyi.business.service.product.TbProductService;
import com.ruoyi.business.service.product.TbProductSkusService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品主表Service实现类
 *
 * @author ruoyi
 * @date 2025-10-29
 */
@Service
@RequiredArgsConstructor
public class TbProductServiceImpl extends ServiceImpl<TbProductMapper, TbProduct> implements TbProductService {
    private final TbProductMapper baseMapper;
    private final TbProductSkusService tbProductSkusService;
    private final TbProductCategoriesService tbProductCategoriesService;
    @Override
    public TableDataInfo<TbProductVO> selectPageList(TbProduct tbProduct, PageQuery pageQuery) {
        LambdaQueryWrapper<TbProduct> eq=getQueryWrapper(tbProduct);
        eq.orderByAsc(TbProduct::getSortOrder);
        Page<TbProduct> page = baseMapper.selectPage(pageQuery.build(), eq);
        //TbProduct转TbProductVO
        List<TbProductVO> tbProductVOS = coveToTbProductVO(page.getRecords());
        //查询商品SKU
        tbProductVOS.forEach(tbProductVO -> {
            List<TbProductSkus> list = tbProductSkusService.list(new LambdaQueryWrapper<>(TbProductSkus.class)
                .eq( TbProductSkus::getProductId, tbProductVO.getId()));
            tbProductVO.setSkusList(list);
            TbProductCategories byId = tbProductCategoriesService.getById(tbProductVO.getCategoryId());
            if (byId != null){
                tbProductVO.setCategoryName(byId.getName());
            }
        });
        Page<TbProductVO> productPage=new Page<>();
        productPage.setRecords(tbProductVOS);
        productPage.setPages(page.getPages());
        productPage.setTotal(page.getTotal());
        productPage.setCurrent(pageQuery.getPageNum());
        productPage.setSize(pageQuery.getPageSize());
        return TableDataInfo.build(productPage);
    }

    private List<TbProductVO> coveToTbProductVO(List<TbProduct> records) {
        //TbProduct 转TbProductVO
        return records.stream().map(tbProduct -> {
            TbProductVO tbProductVO = new TbProductVO();
            BeanUtils.copyProperties(tbProduct, tbProductVO);
            return tbProductVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<TbProduct> selectlist(TbProduct tbProduct) {
        LambdaQueryWrapper<TbProduct> eq=getQueryWrapper(tbProduct);
        List<TbProduct> tbProducts = baseMapper.selectList(eq);
        return tbProducts;
    }

    @Override
    public TbProductVO selectById(Long id) {
        TbProduct tbProduct = baseMapper.selectById(id);
        if (tbProduct != null) {
            TbProductVO tbProductVO = new TbProductVO();
            BeanUtils.copyProperties(tbProduct, tbProductVO);
            List<TbProductSkus> list = tbProductSkusService.list(new LambdaQueryWrapper<>(TbProductSkus.class)
                .eq( TbProductSkus::getProductId, id)
                .eq(TbProductSkus::getStatus, 1).ne(TbProductSkus::getExchangeType, 0));
            tbProductVO.setSkusList(list);
            return tbProductVO;
        }
        return null;
    }

    private LambdaQueryWrapper<TbProduct> getQueryWrapper(TbProduct tbProduct) {
        return Wrappers.lambdaQuery(TbProduct.class).eq(TbProduct::getIsDelete, 0)
            .like(StringUtils.isNotEmpty(tbProduct.getTitle()), TbProduct::getTitle, tbProduct.getTitle())
            .like(StringUtils.isNotEmpty(tbProduct.getSpuCode()), TbProduct::getSpuCode, tbProduct.getSpuCode())
            .eq(tbProduct.getCategoryId() != null, TbProduct::getCategoryId, tbProduct.getCategoryId())
            .like(StringUtils.isNotEmpty(tbProduct.getSearchKeywords()), TbProduct::getSearchKeywords, tbProduct.getSearchKeywords())
            .like(StringUtils.isNotEmpty(tbProduct.getSubtitle()), TbProduct::getSubtitle, tbProduct.getSubtitle())
            .eq(tbProduct.getStatus() != null, TbProduct::getStatus, tbProduct.getStatus())
            .eq(tbProduct.getIsHot() != null, TbProduct::getIsHot, tbProduct.getIsHot())
            .eq(tbProduct.getIsNew() != null, TbProduct::getIsNew, tbProduct.getIsNew())
            .eq(tbProduct.getIsRecommend() != null, TbProduct::getIsRecommend, tbProduct.getIsRecommend())
            .eq(tbProduct.getIsPoints()!=null, TbProduct::getIsPoints, tbProduct.getIsPoints())
            .between(tbProduct.getParams().get("beginTime") != null && tbProduct.getParams().get("endTime") != null,
                TbProduct::getCreateTime, tbProduct.getParams().get("beginTime"), tbProduct.getParams().get("endTime"));
    }

    @Override
    public Boolean deleteByIds(List<Long> ids) {
        TbProduct tbProduct = new TbProduct();
        tbProduct.setIsDelete(1);
        LambdaQueryWrapper<TbProduct> in = new LambdaQueryWrapper<TbProduct>().in(TbProduct::getId, ids);
        return this.update(tbProduct, in);
    }


    // 继承 BaseServiceImpl，自动实现基础 CRUD 方法
    // 如需自定义业务逻辑，重写或新增方法
    // 示例：新增商品前校验SPU编码唯一性
    /*@Override
    public boolean save(TbProduct product) {
        // 校验SPU编码是否已存在
        if (baseMapper.exists(new QueryWrapper<TbProduct>().eq("spu_code", product.getSpuCode()))) {
            throw new ServiceException("SPU编码已存在");
        }
        return super.save(product);
    }*/
}
